package cn.example.networktest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

import cn.example.networktest.utils.HttpUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_send_request;
    private TextView tv_response;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_send_request = (Button) findViewById(R.id.btn_send_request);
        tv_response = (TextView) findViewById(R.id.tv_response);
        btn_send_request.setOnClickListener(this);

        HttpUtil.sendHttpRequest("url", new HttpUtil.HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

            }

            @Override
            public void onError(Exception e) {

            }
        });

        HttpUtil.sendOkHttpRequest("url", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });
    }

    @Override
    public void onClick(View view) {
        if (view.getId()==R.id.btn_send_request){
            sendRequestWithHttpURLConnection();
            //okHttpRequestWithUrl();
        }
    }

    /**
     * okhttprequest 的使用方式
     */
    private void okHttpRequestWithUrl() {
        /*
         有参数的使用办法
         */
       // OkHttpClient.Builder builder = new OkHttpClient.Builder().proxy(Proxy.NO_PROXY);

        new Thread(()->{
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url("http://square.github.io/okhttp/#examples").build();
            try {
                Response response = client.newCall(request).execute();
                String s = response.body().string();
                showResponse(s);
                //请求的写法
                FormBody formBody = new FormBody.Builder().add("name", "2").add("pass", "asda").build();
                Request build = new Request.Builder().post(formBody).build();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * HttpURLConnection 的使用方式
     */
    private void sendRequestWithHttpURLConnection() {

        //开启线程发送网络请求
        new Thread(()->{
            HttpURLConnection   httpURLConnection=null;
            BufferedReader bufferedReader=null;
            try {
                URL url = new URL("http://square.github.io/okhttp/#examples");
                httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setConnectTimeout(8000);
                httpURLConnection.setReadTimeout(8000);
                httpURLConnection.setRequestMethod("GET");

                InputStream stream = httpURLConnection.getInputStream();
                bufferedReader=new BufferedReader(new InputStreamReader(stream));

                StringBuilder response = new StringBuilder();
                String line="";
                while((line=bufferedReader.readLine())!=null){
                    response.append(line);
                }
                showResponse(response.toString());
                //发送写法
                /*OutputStream outputStream = httpURLConnection.getOutputStream();
                DataOutputStream stream1 = new DataOutputStream(outputStream);
                stream1.writeBytes("name=123&pass=1");*/
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (bufferedReader!=null){
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(httpURLConnection!=null){
                    httpURLConnection.disconnect();
                }
            }


        }).start();
    }
    private void showResponse(final String s) {
        //处理更新UI
      runOnUiThread(()->{
        tv_response.setText(s);
      });

    }
}
